<template>
  <section>
    <el-card class="margin-top">
      <div slot="header" class="clearfix relative">
        <el-row>
          <el-col
            :sm="24"
            :md="24"
            :lg="12"
            :xl="12"
            class="flex  align-center justify-start"
          >
            <span class="title-icon margin-right">发货跟踪信息</span>
          </el-col>
          <el-col
            :sm="23"
            :md="23"
            :lg="11"
            :xl="11"
            class="flex  align-center justify-end"
          >
            <el-button
              v-if="isEdit"
              type="success"
              size="mini"
              @click="changeCargoInfo"
            >
              保存仓库地址
            </el-button>
          </el-col>
          <el-col
            :sm="1"
            :md="1"
            :lg="1"
            :xl="1"
            class="text-right flex align-center"
            style="justify-content: flex-end;"
          >
            <i
              :class="{
                'el-icon-arrow-down': show,
                'el-icon-arrow-up': !show
              }"
              class="text-lg pointer margin-left"
              @click="show = !show"
            />
          </el-col>
        </el-row>
      </div>

      <div v-show="show">
        <hot-table
          ref="hotTable"
          :settings="hotSettings"
          :data="shipmentTrackingInfo"
        />
      </div>
    </el-card>
  </section>
</template>

<script>
import { HotTable } from '@handsontable/vue'
// import Handsontable from 'handsontable'
import 'handsontable/languages/zh-CN'
import globalData from '@/utils/config'
import { checkRowsEmpty } from '@/utils/waybill-public'
import { batchSaveAbroadTrackAddress } from '@/api/abroadWaybill'
import { mapGetters } from 'vuex'
export default {
  name: 'DeliveryInfo',
  components: {
    HotTable
  },
  props: {
    shipmentTrackingInfo: {
      type: Array,
      default: function() {
        return []
      }
    },
    oldShipmentTrackingInfo: {
      type: Array,
      default: function() {
        return []
      }
    },
    actionUrl: {
      type: String,
      default: ''
    },
    waybillId: [String, Number],
    isEdit: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      uploadDialog: false,
      show: false,
      fbaCodeList: [],
      autoHeight: 'auto',
      waybillGoodsInfos: [{}, {}, {}, {}, {}]
    }
  },
  computed: {
    ...mapGetters(['publicData']),
    hotSettings() {
      return {
        rowHeaders: true, // 行表头
        stretchH: 'all', // 所有列宽小于表宽时,填充满整个表 all（所有列填充）/last（最后一列）/none(不填充)
        licenseKey: globalData.licensekey,
        // 定义表结构
        colHeaders: ['FBA仓库地址', '派送方式', '追踪号', '快递公司', '备注'],
        width: '100%',
        height: this.autoHeight,

        columns: [
          {
            data: 'dispatchAddressCodeName', // 指定所指列
            width: 100,
            type: 'dropdown',
            source: async (query, process) => {
              const s = this.fbaCodeList.filter(x => x.indexOf(query) > -1)
              process(s)
            }
          },
          {
            data: 'dispatchWay',
            width: 100,
            type: 'dropdown',
            source: ['卡车派送', '快递派送']
          },
          {
            data: 'trackNumber',
            width: 100,
            type: 'text'
          },
          {
            data: 'expressAddress',
            width: 100,
            type: 'text'
          },
          {
            data: 'remark',
            width: 100,
            type: 'text'
          }
        ],
        tableClassName: ['first-class-name', 'second-class-name'],
        language: 'zh-CN',
        contextMenu: ['row_above', 'row_below', 'remove_row', 'alignment'], // 开启右键菜单
        beforeRemoveRow: (index, amount, physicalRows, source) => {
          if (this.shipmentTrackingInfo.length === 1) {
            this.shipmentTrackingInfo.push({})
          }
        },
        afterCreateRow: (index, amount, source) => {
          // console.log('index :>> ', index)
          // this.shipmentTrackingInfo[index].waybillId = this.waybillId
        }
      }
    }
  },
  watch: {
    shipmentTrackingInfo: {
      handler(newValue, oldValue) {
        if (newValue.length === 0) {
          this.$emit('update:shipmentTrackingInfo', [{}])
        } else if (
          newValue.length > 0 &&
          this.publicData.shippingfbaStockList &&
          this.publicData.shippingfbaStockList.length > 0
        ) {
          for (const i of newValue) {
            const a = this.publicData.shippingfbaStockList.find(
              x => x.fbaCode === i.dispatchAddressCode
            )
            if (a) {
              i.dispatchAddressCodeName = `${a.address}(${a.fbaCode})`
            }
          }
        }
        const length = newValue.length
        if (length < 3) {
          this.autoHeight = '250px'
        } else {
          this.autoHeight = 'auto'
        }
      }
      // deep: true,
      // immediate: true
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      const arr = []
      if (
        this.publicData.shippingfbaStockList &&
        this.publicData.shippingfbaStockList.length > 0
      ) {
        for (const i of this.publicData.shippingfbaStockList) {
          arr.push(`${i.address}(${i.fbaCode})`)
        }
      }
      this.fbaCodeList = arr
    },
    closeDialog() {
      this.uploadDialog = false
    },
    changeCargoInfo() {
      const h = this.shipmentTrackingInfo.filter(x => checkRowsEmpty(x))
      if (h.length === 0) {
        this.$message.error('数据为空！')
        return
      }

      for (const i of h) {
        i.dispatchAddressCode = i.dispatchAddressCodeName.slice(
          i.dispatchAddressCodeName.indexOf('(') + 1,
          i.dispatchAddressCodeName.length - 1
        )

        if (
          i.dispatchAddressCodeName &&
          !this.fbaCodeList.includes(i.dispatchAddressCodeName)
        ) {
          this.$message.error('请选择FBA仓库地址')
          return
        }
        if (
          i.dispatchWay &&
          !['卡车派送', '快递派送'].includes(i.dispatchWay)
        ) {
          this.$message.error('请选择派送方式')
          return
        }
        if (!i.waybillId) {
          i.waybillId = this.waybillId
        }
      }
      console.log('h :>> ', h)
      // return
      this.saveInfo(h)
    },
    async saveInfo(h) {
      this.$store.dispatch('app/toggleDialog', true)

      // 标记已删除数据
      const arr = []
      for (const i of this.oldShipmentTrackingInfo) {
        const target = h.find(x => x.id === i.id)
        console.log('target :>> ', target)
        if (!target) {
          i.isDel = true
          arr.push(i)
        }
      }

      const params = [...h, ...arr]

      const { code, message } = await batchSaveAbroadTrackAddress({
        abroadTrackAddress: params
      })

      if (code === 200) {
        this.$message({
          type: 'success',
          message: '保存成功'
        })
      } else {
        this.$message.error(message)
      }
      this.$store.dispatch('app/toggleDialog', false)
    }
  }
}
</script>

<style lang="scss" scoped>
.relative {
  .absolute {
    right: 10px;
    top: -40%;
  }
}
</style>
<style scoped>
/deep/ .el-card__header {
  padding: 8px 20px;
}
</style>
